package com.example.xss.config.serialize;

import cn.hutool.core.util.EnumUtil;
import com.example.xss.commom.enums.IBaseEnum;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;
import java.util.Arrays;

/**
 * 枚举序列化器
 *
 * @author WANGJIET24
 * @date 2021-6-8$
 */
public class EnumDescSerialize extends JsonSerializer<IBaseEnum> implements ContextualSerializer {


    /**
     * 序列化
     * @param value
     * @param gen
     * @param serializers
     * @throws IOException
     */
    @Override
    public void serialize(IBaseEnum value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeObject(value.getValue());
        gen.writeObjectField(gen.getOutputContext().getCurrentName() + "Label", value.getDesc());
    }

    /**
     * 筛选序列化器
     * @param serializerProvider
     * @param beanProperty
     * @return
     * @throws JsonMappingException
     */
    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty==null) {
            return serializerProvider.findNullValueSerializer(null);
        }
        // 如果不是枚举就带走
        if (!EnumUtil.isEnum(beanProperty.getType().getRawClass())) {
            return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
        }
        // 判断当前字段是否继承了 IBaseEnum
        if (!Arrays.asList(beanProperty.getType().getRawClass().getInterfaces()).contains(IBaseEnum.class)) {
            return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
        }
        // 上面的都满足。是枚举类，并且继承了IBaseEnum,就使用我们的序列化方式
        return new EnumDescSerialize();
    }
}
